import { defineStore } from 'pinia'
import { ref } from 'vue'
import { editUserInfoAPI, editUserAvatarAPI } from '@/service/user/user.ts'
import { getEvnAvatarBaseUploadUrl } from '@/utils'
const VITE_UPLOAD_BASEURL = `${getEvnAvatarBaseUploadUrl()}`

const initState = { username:'', nickname: '', avatar: '', token: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })
		// const userInfo = ref<IUserInfo>({
		// 	avatar: "https://artist-eyes.obs.cn-south-1.myhuaweicloud.com/ppd/avatar/4/avatar_2024-11-06_16-57-36.png",
		// 	cellphone: "18903718023",
		// 	email: null,
		// 	gender: "unknown",
		// 	id: 4,
		// 	nickname: "风华绝代",
		// 	openid: "obc-N7TBx2Mwe4T74GT-qPnNVcXg",
		// 	state: "enabled",
		// 	token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzE2MzMxNjYsInN1YiI6IjQifQ.VuqAgL_zB3KhGLtGyMT-y0BTc6NZndVO4lPNL3Yb3V0",
		// 	username: "wx_JfitOO0t9RsJN846",
		// })

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }
		
		const setUserNickname = async (nickname: string) => {
			// 确保 userInfo.value 是对象，而不是空字符串
			if (typeof userInfo.value !== 'object') {
				userInfo.value = { ...initState }
			}
			const user = {
				"nickname":nickname
			}
			const response = await editUserInfoAPI(userInfo.value.id,user);
			console.log(response)
			userInfo.value.nickname = response.nickname
		}
		
		const setUserAvatar = (imagePath: string) => {
			const user_id = userInfo.value.id
			uni.uploadFile({
			  url: VITE_UPLOAD_BASEURL,
			  filePath: imagePath,
			  name: 'image',
			  formData: { user_id },
			  success: (res) => {
			    const parsedData = JSON.parse(res.data) // 将字符串解析为 JSON 对象
			    console.log('uni.uploadAvatar success->', parsedData)
					userInfo.value.avatar = parsedData.avatar
			  },
				fail: (err) => {
					console.log(err)
				}
			})
		}

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(() => !!userInfo.value.token)

    return {
      userInfo,
      setUserInfo,
			setUserAvatar,
			setUserNickname,
      clearUserInfo,
      isLogined,
      reset,
    }
  },
  {
    persist: true,
  },
)
